package org.totoro.memory.jmm;

import org.openjdk.jcstress.annotations.*;
import org.openjdk.jcstress.infra.results.I_Result;

/**
 * 重排序测试
 * <p>
 * 配合 jitwatch 查看重排序代码
 * <p>
 * 参考地址：https://app.yinxiang.com/shard/s45/nl/10505682/e65cbe03-6ea9-45eb-b5e4-281e80b4415a
 * https://app.yinxiang.com/shard/s45/nl/10505682/92262eaf-2200-4d62-a1c5-530d15f176fd
 * <p>
 * jvm 参数：  -XX:+UnlockDiagnosticVMOptions  -XX:+PrintAssembly -XX:+LogCompilation -XX:LogFile=jit.log
 *
 * <p>
 * <p>
 * 常见错误
 * <p>
 * Could not load hsdis-amd64.dylib; library not loadable; PrintAssembly is disabled
 * <p>
 * 需要下载 <a href='https://github.com/evolvedmicrobe/benchmarks/blob/master/hsdis-amd64.dylib'>hsdis-amd64.dylib </a> 然后移动到 jre lib 目录。
 * <p>
 * $ sudo mv hsdis-amd64.dylib /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib
 *
 * @author daocr
 * @date 2020/2/29
 */

@JCStressTest
@Outcome(id = {"1", "4"}, expect = Expect.ACCEPTABLE, desc = "意料结果")
@Outcome(id = {"0"}, expect = Expect.ACCEPTABLE_INTERESTING, desc = "意外结果")
@State
public class JmmReOrdered {

    /**
     * 测试方法
     * <p>
     * 1、 mvn clean install -DskipTests=true
     * 2、 java -jar target/jcstress.jar
     * 3、观察意外结果数量
     */
    int num = 0;
    boolean ready = false;

    @Actor
    public void method(I_Result result) {
        if (ready) {
            result.r1 = num + num;
        } else {
            result.r1 = 1;
        }
    }

    @Actor
    public void method2(I_Result result) {
        num = 2;
        ready = true;
    }

}
